{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "101d4a64-b1d6-4318-81e2-d549ef64e45b",
   "metadata": {},
   "source": [
    "Chapter 09\n",
    "# 定义、使用“列表统计量”类，使用装饰器\n",
    "Book_1《编程不难》 | 鸢尾花书：从加减乘除到机器学习  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "fbd2b389-efa6-4862-a0a2-18884a8547a2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 定义了一个 ListStatistics 类\n",
    "class ListStatistics:\n",
    "    # 构造函数，用于初始化属性\n",
    "    def __init__(self):\n",
    "        self._data = []\n",
    "    \n",
    "    @property\n",
    "    # @property 将方法转换为只读属性\n",
    "    def data(self):\n",
    "        return self._data\n",
    "    \n",
    "    @data.setter\n",
    "    # setter 设置属性时执行一些逻辑或验证\n",
    "    def data(self, new_list):\n",
    "        if self._are_all_numeric(new_list):\n",
    "            self._data = new_list\n",
    "        else:\n",
    "            print(\"错误：列表中元素必须全部是数值\")\n",
    "            \n",
    "    @classmethod\n",
    "    # @classmethod 装饰器用于定义类方法\n",
    "    # 逐个判断列表所有元素是否都是数值\n",
    "    def _are_all_numeric(cls, input_list):\n",
    "        for element in input_list:\n",
    "            if not isinstance(element, (int, float)):\n",
    "                return False\n",
    "        return True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "474eac04-3fec-4e0e-be81-49d701a15b8e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建一个浮点数列表\n",
    "data = [8.8, 1.8, 7.8, 3.8, 2.8, 5.6, '3.9', 6.9]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "58771c52-4055-4ade-99f1-481d7827ff8e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建实例\n",
    "float_list_obj = ListStatistics()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "38c73a7c-f10b-494b-ae58-5cf042c042c6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "错误：列表中元素必须全部是数值\n"
     ]
    }
   ],
   "source": [
    "# 尝试设置含非数值元素的列表，会输出错误消息\n",
    "float_list_obj.data = data"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
